<script setup lang="ts">
import { ref, isVNode } from 'vue'

// 表头配置的属性同el-table-column的属性。不支持多级表头
const props = withDefaults(
	defineProps<{
		columns: {
			prop: string
			label: string
			contentRender?: (scope: { [key: string]: any }) => any
			headerRender?: (scope: { [key: string]: any }) => any
			[key: string]: any
		}[]
		initPageSzie?: number
		initPageNum?: number
	}>(),
	{ initPageSzie: 20, initPageNum: 1 }
)

const pageSize = ref(props.initPageSzie)
const pageNum = ref(props.initPageNum)

function reset() {
	pageNum.value = 1
	pageSize.value = props.initPageSzie
}

defineExpose({
	pageNum,
	pageSize,
	reset,
})
</script>

<template>
	<!-- row-key:用于优化渲染，指的是data中每一项的key，和antd-vue一样 -->
	<el-table v-bind="$attrs">
		<div slot="empty" v-if="!$attrs['empty-text']">
			<slot name="empty">暂无数据</slot>
		</div>
		<!--body { row, column, $index } -->
		<!--header { column, $index } -->
		<template v-for="item in columns" :key="item.prop">
			<el-table-column v-bind="item">
				<template #default="scope: any">
					<!-- 填补列内容插槽时，使用prop的具名形式填充 -->
					<slot :name="item.prop" v-bind="scope">
						<component v-if="item.contentRender && isVNode(item.contentRender(scope))" :is="item.contentRender(scope)" />
						<template v-else>{{ item.contentRender ? item.contentRender(scope) : scope.row[item.prop] }}</template>
					</slot>
				</template>
				<template #header="scope:any">
					<!-- 填补列头部插槽时，使用prop-header的具名形式填充 -->
					<slot :name="`${item.prop}-header`" v-bind="scope">
						<component v-if="item.headerRender && isVNode(item.headerRender(scope))" :is="item.headerRender(scope)" />
						<template v-else>{{ item.headerRender ? item.headerRender(scope) : item.label }}</template>
					</slot>
				</template>
			</el-table-column>
		</template>
	</el-table>

	<div class="table-pagination-container" style="margin: 10px 0; display: flex; justify-content: flex-end" v-if="$attrs.pagination">
		<el-pagination v-bind="$attrs.pagination" v-model:current-page="pageNum" v-model:page-size="pageSize" />
	</div>
</template>

<style scoped></style>
